﻿using Aspose.Pdf;
using Microsoft.AspNetCore.Mvc;
using Microsoft.CodeAnalysis.VisualBasic.Syntax;
using Microsoft.IdentityModel.Tokens;
using NaturalNote.Core;

namespace XxSystem.FileManager.Controllers
{
    public class ConvertToTask
    {
        static string rootPath = "Y:\\books\\";
        static Queue<string> files = new Queue<string>();
        public static void add(string path) {
            files.Enqueue(path);
        }
        public static void run() 
        {
            while (true) 
            {
                if (files.Count > 0) 
                {
                    var f = files.Dequeue();
                    Console.WriteLine(f);
                    SaveCover(f);
                } else 
                {
                    Thread.Sleep(10000);
                }
            }
        }
        public static void SaveCover(string path)
        {
            var dir = Base64UrlEncoder.Decode(path);
            var pdfPath = Path.Combine(rootPath, dir);
            // load PDF with an instance of Document                        

            var md5Path = HashUtil.Md5(Base64UrlEncoder.Encode(dir));
            var truePath = $"H:\\obj_file_cover\\{md5Path.Substring(0, 2)}\\{md5Path.Substring(2, 4)}";
            if (!Directory.Exists(truePath))
            {
                Directory.CreateDirectory(truePath);
            }
            // convert a particular page and save the image in EMF format
            var orgJpgPath = $"{truePath}\\{md5Path.Substring(6)}.jpg";
            if (!System.IO.File.Exists(orgJpgPath))
            {
                using var document = new Document(pdfPath);
                // create an object of EmfDevice
                var renderer = new Aspose.Pdf.Devices.JpegDevice();
                renderer.Process(document.Pages[1], orgJpgPath);
            }
            var orgJpgNewPath = $"{truePath}\\{md5Path.Substring(6)}_80_100.jpg";

            if (!System.IO.File.Exists(orgJpgNewPath))
            {
                ImgCovert.SaveNewSize(orgJpgPath, 80, 100, orgJpgNewPath);
            }
        }
    }
}
